import React from 'react'
import {connect} from 'react-redux'
import {get} from '../../../fetch/get.js'

import ListComponent from '../../../components/List'
import LoadMore from '../../../components/LoadMore'

const initialState ={
    data: [],
    hasMore: false,
    isLoadingMore: false,
    page: 0
}

class SearchList extends React.Component{
    constructor(props, context){
        super(props, context)
        this.state = initialState
    }
    render() {
        return (
            <div>
                {
                    this.state.data.length
                    ? <ListComponent data={this.state.data}></ListComponent>
                    : <div>加载中@@@@</div>
                }
                {
                    this.state.hasMore
                    ? <LoadMore loadMoreFn={this.loadMoreData.bind(this)}></LoadMore>
                    : '最后啦'
                }
            </div>
        )
    }
    componentDidMount() {
        console.log(123)
        this.loadFirstPageData()
    }
    componentDidUpdate(prevprops) {
        const key = this.props.key
        const type = this.props.type
        //当搜索条件相同时   忽略
        if(key === prevprops.key && type === prevprops.type){
            return
        }
        //重置state
        this.setState(initialState)
        //重新加载数据
        this.loadFirstPageData()
    }

    loadFirstPageData() {  //获取首屏数据
        const cityName = this.props.userinfo.cityName
        const page = 0
        const result = get('/api/homelist/' + cityName +'/' + page)
        this.resultHandle(result)
    }

    loadMoreData() { //加载更多数据
        //记录状态
        this.setState(
            {
                isLoadingMore: true
            }
        )
        const cityName = this.props.userinfo.cityName
        const page = this.state.page
        const result = get('/api/homelist/' + cityName +'/' + page)
        this.resultHandle(result)

        this.setState({
            page: page + 1,
            isLoadingMore: false
        })
    }

    resultHandle(result) {
        result.then((res) => {
            return res.json()
        }).then((json) => {
            const hasMore = json.hasMore
            const data = json.data
            this.setState({
                hasMore: hasMore,
                data: this.state.data.concat(data)
            })
        })
    }
}


function mapStateToProps(state) {
    return {
        userinfo: state.userinfo
    }
}

function mapDispatchToProps() {
    return {

    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(SearchList)